<script setup lang="ts">
const num1 = ref(1)
const num2 = ref(2)
const ops = ["+", "-"]
const op = ref('')
const yourAns = ref('')
const curAns = ref('')
const showScore = ref(false)
const ansList = ref<{ title: string, yourAns: string, isRight: boolean }[]>([])
let usedTime = 0
const MAXNUMS = 10
const isPhone = ref(false)

const buildSubject = () => {
  num1.value = Math.ceil(Math.random() * range.value)
  num2.value = Math.ceil(Math.random() * range.value)
  op.value = type.value === '*' ? ops[Math.round(Math.random())] : type.value
  if (op.value === '-') {
    if (num1.value < num2.value) {
      // 交换num1和num2的值
      const temp = num1.value
      num1.value = num2.value
      num2.value = temp
    }
  }
  setTimeout(() => {
    refInput.value.focus()
  })

}
const range = ref(50)
const type = ref('+')
onMounted(() => {
  buildSubject()

  isPhone.value = !!navigator.userAgent.match(
    /(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i
  )
})
let startTime = 0

const showRecord = () => {
  let record = localStorage.getItem('record' + range.value)
  if (record) {
    if (usedTime < Number(record)) {
      localStorage.setItem('record' + range.value, usedTime.toString())
      alert('恭喜您破纪录啦！用时' + usedTime + '秒')
    } else {
      alert('太可惜了，本次用时' + usedTime.toString() + '秒，而您的最好记录是' + record + '秒')
    }
  } else {
    localStorage.setItem('record' + range.value, usedTime.toString())
    alert('恭喜您，创了新记录！用时' + usedTime + '秒')
  }
}
const submit = () => {
  if (ansList.value.length === 0) {
    // 开始计
    startTime = Date.now()
  }

  curAns.value = eval(`${num1.value} ${op.value} ${num2.value}`)
  ansList.value.push({
    title: `${num1.value} ${op.value} ${num2.value}`,
    yourAns: yourAns.value,
    isRight: yourAns.value == curAns.value
  })

  if (ansList.value.length === MAXNUMS) {
    usedTime = Math.round((Date.now() - startTime) / 1000)
    showScore.value = true
    if (curScore.value === 100) {
      showRecord()
    }
  }

  yourAns.value = ''

  // if (yourAns.value == curAns.value) {
  //   alert('恭喜你答对了')
  // } else {
  //   alert('很遗憾，答错了')
  // }
  buildSubject()
}
const refInput = ref()
const again = () => {
  ansList.value = []
  showScore.value = false

  buildSubject()
}
watch([type, range], (newVal) => {
  buildSubject()
})
const hClick = (item: number) => {
  yourAns.value += item
  refInput.value.focus()
}
const hClear = () => {
  yourAns.value = ''
  refInput.value.focus()

}

const curScore = computed(() => {
  return Math.ceil((ansList.value.filter(item => item.isRight).length / ansList.value.length) * 100)
})

const addToHomeScreen = () => {
  console.log(1)
  // if (window.navigator && window.navigator.standalone) {
  //   alert('请点击分享按钮，然后选择添加到主屏幕')
  // } else if (window.matchMedia('(display-mode: standalone)').matches) {
  alert('请点击菜单或者分享按钮，然后选择"添加到主屏幕"')
  // } else {
  //   alert('浏览器打开')
  // }
}

</script>

<template>
  <main class="w-96 mx-auto mt-8 px-8">
    <div v-show="!showScore" class="flex justify-center items-center">
      <div class="mx-auto">
        <div>运算：
          <input type="radio" name="type" v-model="type" value="+" /> + &nbsp;&nbsp;
          <input type="radio" name="type" v-model="type" value="-" /> - &nbsp;&nbsp;
          <input type="radio" name="type" v-model="type" value="*" /> -或者+
        </div>
        <div>范围：
          <input type="radio" name="range" v-model="range" :value="50" id="n10" /> <label
            for="n10">50以内</label>&nbsp;&nbsp;
          <input type="radio" name="range" v-model="range" :value="100" id="n10" /> <label
            for="n10">100以内</label>&nbsp;&nbsp;
          <input type="radio" name="range" v-model="range" :value="200" id="n20" /> <label for="n20">200以内</label>
        </div>
      </div>
    </div>
    <div v-show="!showScore" class="flex justify-center items-center text-6xl text-center mb-4 mt-10">
      <div>{{ num1 }}</div>
      <div>{{ op }}</div>
      <div>{{ num2 }}</div>
      <div>=</div>
      <input ref="refInput" class="outline-1 border-2 rounded-3xl text-5xl px-4 h-20 py-2 text-center w-32 mx-2"
        v-model="yourAns" readonly type="text" @keyup.enter="submit" />
    </div>
    <div v-show="!showScore" class="grid grid-cols-3 gap-6 m-2">
      <button class="bg-orange-200 border-2 rounded-xl h-12" @click="hClick(item - 1)" v-for="item in 10" :key="item">{{
        item
        - 1 }}</button>
      <button @click="hClear">清空</button>
      <button @click="submit" class="border-2 rounded p-2">确定</button>

    </div>
    <div v-show="showScore" class="flex mt-12 justify-center items-center text-xl leading-relaxed">
      <div class="p-4 border-2 rounded-2xl bg-slate-300 flex justify-center flex-col">
        <h3 class="text-center text-2xl mb-4">成绩单</h3>

        <div><span>用时：{{ usedTime }}秒</span>&nbsp;&nbsp;&nbsp;<span>得分：<span class="text-orange-500">
              {{ curScore }} </span>分</span></div>

        <ol class="grid grid-cols-2 gap-4 m-2">
          <li v-for="(item, idx) in ansList" :key="idx">
            <span :class="item.isRight ? 'text-slate-950' : 'text-red-500'">{{ item.title }} = {{
              item.yourAns }}
            </span>
          </li>
        </ol>
        <button @click="again" class="bg-orange-200 border-2 rounded-xl">再来一次</button>
      </div>

    </div>
    <!-- <button v-show="isPhone" class="container mt-8 bg-green-500 border-2 rounded-xl h-12"
      @click="addToHomeScreen">添加到主屏幕</button> -->

  </main>
</template>
